//logs.js
const app = getApp();
let api = require("../../api/api.js")

Page({
  data: {
    hasSend: false, // 是否已经发送
    sendCount: 60,
    message:"",
    mobilePhone: '',
    agree: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },
  onLoad: function () {
    
  },
  // 输入框改变
  changeInput: function(e) {
    let type = e.currentTarget.dataset.type;
    if (type == 'mobilePhone') {
      this.setData({
        mobilePhone: e.detail.value
      })
    } else if (type == 'message') {
      this.setData({
        message: e.detail.value
      })
    } 
  },

  //用户协议同意
  checkboxChange: function(e){
    this.setData({ agree: !this.data.agree })
    console.log(this.data.agree)
  },

  // 校验验证码
  loginAndRegister: function() {
    const mobilePhone$ = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/;
    const { mobilePhone, message } = this.data;
    const that = this;

    if (mobilePhone == '') {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (!mobilePhone$.test(mobilePhone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (message == '') {
      wx.showToast({
        title: ' 短信验证码不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if( !this.data.agree ){
      wx.showToast({
        title: '请同意用户服务协议',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    /**
     * 登录请求
     */
    api.userLogin(mobilePhone, message)
  },

  // 发送验证码
  sendMessage: function() {
    const mobilePhone$ = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/;
    const { mobilePhone, hasSend } = this.data;
    console.log(mobilePhone)
    const that = this;
    if (hasSend) return;
    if (mobilePhone == '') {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (!mobilePhone$.test(mobilePhone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    /**
     * 发送获取手机号的请求
     */
    api.mobileCode(mobilePhone).then(res=>{
      that.setData({ hasSend: true })
      wx.hideLoading()
      that.countDown() // 验证码倒计时动画效果
    })
  },


  /**
   * 验证码倒计时动画效果
   */
  countDown:function(){
    let that = this;
    let sendCount = that.data.sendCount
    var interval = setInterval(function(){
      sendCount -= 1;
      that.setData({ sendCount: sendCount })
      if(that.data.sendCount < 0){
        that.setData({ sendCount: 60 })
        that.setData({ hasSend: false })
        clearInterval(interval)
      }
    },1000)
  }   
})
